//
//  GameObject.cpp
//  ComponentSystem
//
//  Created by Jeppe Nielsen on 9/25/14.
//  Copyright (c) 2014 Jeppe Nielsen. All rights reserved.
//

#include "GameObject.hpp"
#include "GameComponent.hpp"
#include "GameWorld.hpp"

GameObject::GameObject() : Parent(this), enabledComponents(0), activeComponents(0), ownedComponents(0) {
    Parent = 0;
    Parent.Changed += Nano::event_handler(this, &GameObject::ParentChanged);
    int numberOfComponents = GameComponentTypeFactory::componentIdCounter;
    components = new Components[numberOfComponents];
    for (int i=0; i<numberOfComponents; ++i) {
        components[i]=0;
    }
}

GameObject::~GameObject() {
    delete [] components;
    delete [] systemIndicies;
}

void GameObject::ParentChanged(Nano::Property<GameObject *, GameObject *>::EventData d) {
    if (d.Old) {
        ObjectCollection::iterator it = std::find(d.Old->children.begin(), d.Old->children.end(), this);
        d.Old->children.erase(it);
    }
    if (d.Current) {
        d.Current->children.push_back(this);
    }
}

void GameObject::Remove() {
    world->removedObjects.insert(this);
    for (size_t i=0; i<children.size(); i++) {
        children[i]->Remove();
    }
}

const ObjectCollection& GameObject::Children() { return children; }

GameObject* GameObject::Clone() {
    return Clone(Parent);
}

GameObject* GameObject::Clone(GameObject* parent) {
    GameObject* clone = world->CreateObject();
    clone->Parent = parent;
    for (size_t i=0; i<world->componentTypes.size(); i++) {
        if (components[i]) {
            world->CloneComponent(clone, (int)i, this);
        }
    }
    
    for (size_t i=0; i<children.size(); i++) {
        children[i]->Clone(clone);
    }
    
    return clone;
}



